package com.elite.groovy.dev;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchInsertExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://127.0.0.1:3306/ques_data?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai";
        String user = "HSDev";
        String password = "letmein";

        String insertQuery = "INSERT INTO yourtable (column1, column2) VALUES (?, ?)";

        long startTime = System.currentTimeMillis();
        try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement pstmt = conn.prepareStatement(insertQuery)) {

            conn.setAutoCommit(false); // 禁用自动提交

            // 批量插入100条数据
            for (int i = 0; i < 4000; i++) {
                pstmt.setInt(1, i);
                pstmt.setString(2, "value" + i);
                pstmt.addBatch(); // 添加到批处理
            }

            // 执行批量操作
            pstmt.executeBatch();

            // 提交事务
            conn.commit();

            System.out.println("Batch insertion completed successfully 耗时(毫秒):" + (System.currentTimeMillis() - startTime));

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}